package com.merchant.home;

import java.util.ArrayList;
import java.util.HashMap;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.merchant.constant.Constants;
import com.merchant.home.CumulativeGainActivity.RunTask;
import com.merchant.json.ReadJson;
import com.merchant.list.RefreshLayout;
import com.merchant.list.RefreshLayout.OnLoadListener;
import com.umeng.analytics.MobclickAgent;
import com.zjxfood.merchant.activity.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

public class OrderDetailGainActivity extends Activity implements
		OnClickListener, OnRefreshListener, OnLoadListener {
	private TextView title_text;// 标题
	// private TextView time;
	private ImageView cumulative_gain_back_image;// 返回
	private TextView order_deteil_text2;// 消费时间
	private TextView order_deteil_text3;// 消费金额
	private TextView order_deteil_text4;// 消费游客
	private TextView order_deteil_text5;// 消费商家
	private TextView order_deteil_text6;// 返时尚币
	private TextView order_deteil_text7;// 营业收入
	private TextView order_deteil_text8;// 收益
	private TextView order_deteil_text1;// 订单�?

	private HashMap<String, Object> mUserMapLists;
	private ArrayList<HashMap<String, Object>> mMap;
	private ArrayList<HashMap<String, Object>> mDataList;
	private ArrayList<HashMap<String, Object>> addDataList;
	String str = null;
	private MyAdapter adapter;
	private String page = "1";
	private int lastVisibleIndex;
	private int x = 1;
	private RunTask mRunTask;
	private PullToRefreshListView lv;
	private ProgressBar progressBar_chun_sr_detail;
	private TextView yycshouru_mingxi;

	// private RefreshLayout mSwipeLayout;
	// private View header;
	private int pagee = 1;
	private String label;
	// 标记数据请求状态，加载或刷新
	private int loading_state = Constants.DATE_ADAPTER_RESET;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_order_detail);
		Bundle bundle = getIntent().getExtras();
		str = bundle.getString("time");
		init();
		mRunTask = new RunTask();
		mRunTask.execute("");
		// new Thread(getbusinessdetailbydate).start();
		setListener();
	}

	@SuppressWarnings("deprecation")
	private void init() {
		title_text = (TextView) findViewById(R.id.cumulative_gain_text);
		yycshouru_mingxi = (TextView) findViewById(R.id.yycshouru_mingxi);
		// time = (TextView) findViewById(R.id.cumulative_time);
		// time.setVisibility(View.GONE);
		if (Constants.mtype.equals("3")) {
			title_text.setText("收益详情");
			yycshouru_mingxi.setText("收益明细");
		} else {
			title_text.setText("收益详情");
			yycshouru_mingxi.setText("收益明细");
		}

		cumulative_gain_back_image = (ImageView) findViewById(R.id.cumulative_gain_back_image);
		cumulative_gain_back_image.setOnClickListener(this);
		lv = (PullToRefreshListView) findViewById(R.id.list_detail1);
		lv.setMode(Mode.BOTH);
		lv.setScrollingWhileRefreshingEnabled(false);
		// lv.setOnScrollListener(mScrollListener);
		progressBar_chun_sr_detail = (ProgressBar) findViewById(R.id.progressBar_chun_sr_detail);
		progressBar_chun_sr_detail.setVisibility(View.VISIBLE);
		lv.setVisibility(View.GONE);
		// mSwipeLayout = (RefreshLayout)
		// findViewById(R.id.list_detail1_swipe_ly);
		// header = getLayoutInflater().inflate(R.layout.header, null);
		// mSwipeLayout.setOnRefreshListener(this);
		// mSwipeLayout.setOnLoadListener(this);
		// mSwipeLayout.setColorSchemeResources(android.R.color.holo_green_dark,
		// android.R.color.holo_green_light,
		// android.R.color.holo_orange_light,
		// android.R.color.holo_orange_dark);
		// order_deteil_text1 = (TextView)
		// findViewById(R.id.order_deteil_text1);
		// order_deteil_text2 = (TextView)
		// findViewById(R.id.order_deteil_text2);
		// order_deteil_text3 = (TextView)
		// findViewById(R.id.order_deteil_text3);
		// order_deteil_text4 = (TextView)
		// findViewById(R.id.order_deteil_text4);
		// order_deteil_text5 = (TextView)
		// findViewById(R.id.order_deteil_text5);
		// order_deteil_text6 = (TextView)
		// findViewById(R.id.order_deteil_text6);
		// order_deteil_text7 = (TextView)
		// findViewById(R.id.order_deteil_text7);
		// order_deteil_text8 = (TextView)
		// findViewById(R.id.order_deteil_text8);
	}

	private void setListener() {
		lv.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				pagee = 1;
				label = DateUtils.formatDateTime(getApplicationContext(),
						System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
								| DateUtils.FORMAT_SHOW_DATE
								| DateUtils.FORMAT_ABBREV_ALL);
				lv.getLoadingLayoutProxy().setRefreshingLabel("正在刷新...");
				lv.getLoadingLayoutProxy().setPullLabel("下拉刷新");
				lv.getLoadingLayoutProxy().setReleaseLabel("松手刷新");
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(
						"上次更新:" + label);
				handler.sendEmptyMessageDelayed(4, 2000);
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				pagee++;
				loading_state = Constants.DATE_ADAPTER_ADD;
				label = DateUtils.formatDateTime(getApplicationContext(),
						System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
								| DateUtils.FORMAT_SHOW_DATE
								| DateUtils.FORMAT_ABBREV_ALL);
				lv.getLoadingLayoutProxy().setRefreshingLabel("正在加载...");
				lv.getLoadingLayoutProxy().setPullLabel("上拉加载更多");
				lv.getLoadingLayoutProxy().setReleaseLabel("松手加载");
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(
						"上次加载:" + label);
				handler.sendEmptyMessageDelayed(5, 2000);
			}
		});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = new Intent();
		switch (v.getId()) {
		case R.id.cumulative_gain_back_image:
			finish();
			break;
		}
	}

	public void onRefresh() {
		handler.sendEmptyMessageDelayed(4, 2000);
	}

	@Override
	public void onLoad() {
		// TODO Auto-generated method stub
		handler.sendEmptyMessageDelayed(5, 500);
	}

	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	class RunTask extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... strs) {
			switch (x) {
			case 1:
				try {
					String ss = "uid=" + Constants.Id + "&isjh=" + false
							+ "&page=" + page + "&pagesize=10" + "&time=" + str;
					String sign = Constants.sortsStr(ss);
					String strr = Constants.getincomedetailbydate + sign
							+ "&uid=" + Constants.Id + "&isjh=" + false
							+ "&page=" + page + "&pagesize=10" + "&time=" + str;
					String json = ReadJson.readParse(strr);
					mUserMapLists = Constants.getJson2Object(json);
					mDataList = Constants.getJsonArray(mUserMapLists
							.get("Data").toString());
					Log.i("mDataList", "================" + mDataList);
					handler.sendEmptyMessageDelayed(1, 0);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					handler.sendEmptyMessageDelayed(3, 0);
					e.printStackTrace();
				}
				break;

			case 2:
				String ss = "uid=" + Constants.Id + "&isjh=" + false + "&page="
						+ page + "&pagesize=10" + "&time=" + str;
				String sign = Constants.sortsStr(ss);
				String strr = Constants.getincomedetailbydate + sign + "&uid="
						+ Constants.Id + "&isjh=" + false + "&page=" + page
						+ "&pagesize=10" + "&time=" + str;
				String json;

				try {
					json = ReadJson.readParse(strr);
					mUserMapLists = Constants.getJson2Object(json);
					addDataList = Constants.getJsonArray(mUserMapLists.get(
							"Data").toString());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					handler.sendEmptyMessageDelayed(3, 0);
					e.printStackTrace();
				}
				handler.sendEmptyMessageDelayed(2, 0);
				break;
			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			boolean hasMoreData = true;
			if (adapter != null) {
				adapter.notifyDataSetChanged();
			}
			lv.onRefreshComplete();
			super.onPostExecute(result);
		}
	}

	// Runnable getbusinessdetailbydate = new Runnable() {
	//
	// @Override
	// public void run() {
	// try {
	// String ss = "uid=" + Constants.Id + "&isjh=" + false + "&page="
	// + 1 + "&pagesize=" + 10 + "&time=" + str;
	// String sign = Constants.sortsStr(ss);
	// String strr = Constants.getincomedetailbydate + sign + "&uid="
	// + Constants.Id + "&isjh=" + false + "&page=" + 1
	// + "&pagesize=" + 10 + "&time=" + str;
	// String json = ReadJson.readParse(strr);
	// mUserMapLists = Constants.getJson2Object(json);
	// mDataList = Constants.getJsonArray(mUserMapLists.get("Data")
	// .toString());
	// Log.i("mDataList", "================" + mDataList);
	// handler.sendEmptyMessageDelayed(1, 0);
	// } catch (Exception e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// }
	// };
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				adapter = new MyAdapter(getApplicationContext(), mDataList);
				// lv.addHeaderView(header);
				lv.setAdapter(adapter);
				progressBar_chun_sr_detail.setVisibility(View.GONE);
				lv.setVisibility(View.VISIBLE);
				break;
			case 2:
				try {
					adapter.nofity(addDataList);
				} catch (Exception e) {
					// TODO: handle exception
					handler.sendEmptyMessageDelayed(6, 0);
				}
				break;
			case 3:
				progressBar_chun_sr_detail.setVisibility(View.GONE);
				lv.setVisibility(View.VISIBLE);
				Toast.makeText(getApplicationContext(), "请检查您的网络链接!",
						Toast.LENGTH_SHORT).show();
				break;
			case 4:
				// try {
				// adapter.notifyDataSetChanged();
				// mSwipeLayout.setRefreshing(false);
				// } catch (Exception e) {
				// // TODO: handle exception
				// handler.sendEmptyMessageDelayed(6, 0);
				// }
				new RunTask().execute();
				break;
			case 5:
				// 更新数据
				// 更新完后调用该方法结束刷新
				x = 2;
				page = Integer.parseInt(page) + 1 + "";
				mRunTask = new RunTask();
				mRunTask.execute("");
				// mSwipeLayout.setLoading(false);
				break;

			case 6:
				Toast.makeText(getApplicationContext(), "请检查您的网络链接!",
						Toast.LENGTH_SHORT).show();
				break;
			}
		};
	};
	OnScrollListener mScrollListener = new OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if (adapter != null) {
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
						&& lastVisibleIndex == adapter.getCount() - 1) {
					x = 2;
					page = Integer.parseInt(page) + 1 + "";
					mRunTask = new RunTask();
					mRunTask.execute("");
				}
			}
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// 计算最后可见条目的索引
			lastVisibleIndex = firstVisibleItem + visibleItemCount - 1;
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// do something here
			finish();
		}

		return super.onKeyDown(keyCode, event);
	}

	public class ViewHolder {
		private TextView order_deteil_text2;// 消费时间
		private TextView order_deteil_text3;// 消费金额
		private TextView order_deteil_text4;// 消费游客
		private TextView order_deteil_text5;// 消费商家
		private TextView order_deteil_text6;// 返时尚币
		private LinearLayout order_deteil_text;// 营业收入
		private TextView order_deteil_text1;// 订单�?
		private TextView order_deteil_text8;// 收益
		private TextView shouyi_or_yjzc;
		private LinearLayout order_deteil_text_ll_10;
		private LinearLayout order_deteil_text_ll_9;
	}

	public static String splitePhone(String phone) {
		String[] tel = new String[phone.length()];
		StringBuffer sb = new StringBuffer();
		if (tel.length > 0) {
			for (int i = 0; i < tel.length; i++) {
				if (i > 2 && i < 7) {
					sb.append("*");
				} else {
					sb.append(phone.charAt(i));
				}
			}
		}
		return sb.toString();
	}

	public class MyAdapter extends BaseAdapter {

		private LayoutInflater flater;
		private ArrayList<HashMap<String, Object>> mList;

		public MyAdapter(Context context,
				ArrayList<HashMap<String, Object>> list) {
			this.flater = LayoutInflater.from(context);
			this.mList = list;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mList.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		public void nofity(ArrayList<HashMap<String, Object>> list) {
			try {
				this.mList.addAll(list);
				notifyDataSetChanged();
			} catch (Exception e) {
				// TODO: handle exception
				handler.sendEmptyMessageDelayed(3, 0);
			}
		}

		@Override
		public View getView(int position, View converView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder hodler = null;
			if (converView == null) {
				hodler = new ViewHolder();
				converView = flater.inflate(R.layout.layout_detail, null);
				hodler.order_deteil_text1 = (TextView) converView
						.findViewById(R.id.order_deteil_consumption_text1);
				hodler.order_deteil_text2 = (TextView) converView
						.findViewById(R.id.order_deteil_consumption_text2);
				hodler.order_deteil_text3 = (TextView) converView
						.findViewById(R.id.order_deteil_consumption_text3);
				hodler.order_deteil_text4 = (TextView) converView
						.findViewById(R.id.order_deteil_consumption_text4);
				hodler.order_deteil_text5 = (TextView) converView
						.findViewById(R.id.order_deteil_consumption_text5);
				hodler.order_deteil_text6 = (TextView) converView
						.findViewById(R.id.order_deteil_consumption_text6);
				hodler.order_deteil_text = (LinearLayout) converView
						.findViewById(R.id.order_deteil_consumption_text);
				hodler.order_deteil_text8 = (TextView) converView
						.findViewById(R.id.order_deteil_consumption_text8);
				hodler.shouyi_or_yjzc = (TextView) converView
						.findViewById(R.id.shouyi_or_yjzc);
				hodler.order_deteil_text_ll_9 = (LinearLayout) converView
						.findViewById(R.id.order_deteil_consumption_text9_ll);
				hodler.order_deteil_text_ll_10 = (LinearLayout) converView
						.findViewById(R.id.order_deteil_consumption_text10_ll);

				converView.setTag(hodler);
			} else {
				hodler = (ViewHolder) converView.getTag();
			}
			hodler.order_deteil_text_ll_9.setVisibility(View.GONE);
			hodler.order_deteil_text_ll_10.setVisibility(View.GONE);
			if (Constants.mtype.equals("2") || Constants.mtype.equals("1")) {
				hodler.shouyi_or_yjzc.setText("收        益:");
			} else {
				hodler.shouyi_or_yjzc.setText("收        益:");
			}
			Log.i("msg", "++++++++++++++++++++++++++++" + mList);
			if (mList.get(position).get("orderid") != null) {
				hodler.order_deteil_text1.setText(mList.get(position)
						.get("orderid").toString());
			} else {
				hodler.order_deteil_text1.setText("");
			}
			if (mList.get(position).get("createtime") != null) {
				hodler.order_deteil_text2.setText(mList.get(position)
						.get("createtime").toString());
			} else {
				hodler.order_deteil_text2.setText("");
			}
			if (mList.get(position).get("money") != null) {
				hodler.order_deteil_text3.setText("¥"
						+ mList.get(position).get("allmoney").toString());
			} else {
				hodler.order_deteil_text3.setText("");
			}
			if (mList.get(position).get("username") != null) {
				hodler.order_deteil_text4.setText(mList.get(position)
						.get("username").toString());
			} else {
				hodler.order_deteil_text4.setText("");
			}

			if (mList.get(position).get("merchantname") != null) {
				hodler.order_deteil_text5.setText(mList.get(position)
						.get("merchantname").toString());
			} else {
				hodler.order_deteil_text5.setText("");
			}
			if (mList.get(position).get("shmoney") != null) {
				hodler.order_deteil_text6.setText("¥"
						+ mList.get(position).get("shmoney").toString());
			} else {
				hodler.order_deteil_text6.setText("");
			}
			// if (mList.get(position).get("realmoney") != null) {
			// hodler.order_deteil_text7.setText("¥"
			// + mList.get(position).get("realmoney").toString());
			// } else {
			// hodler.order_deteil_text7.setText("");
			// }
			hodler.order_deteil_text.setVisibility(View.GONE);
			if (mList.get(position).get("income") != null) {
				hodler.order_deteil_text8.setText("¥"
						+ mList.get(position).get("income").toString());
			} else {
				hodler.order_deteil_text8.setText("");
			}
			return converView;
		}

	}
}
